package semaphore;

import java.sql.Connection;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;

/**
 * 使用Semaphore实现连接池
 */
public class SemaphoreDBPool {

    private final static int MAX_SIZE=10;

    private static LinkedBlockingQueue<Connection> pool=new LinkedBlockingQueue<>();

    private final Semaphore semaphore;

    public SemaphoreDBPool(){
        semaphore=new Semaphore(MAX_SIZE);
    }

    static {
        for (int i=0;i<MAX_SIZE;i++){
            pool.add(new ConnectionImpl());
        }
    }

    public Connection getConnection() throws InterruptedException {
        semaphore.acquire();
        return pool.remove();
    }

    public void returnConnection(Connection connection){
        if(connection!=null){
            System.out.println("当前有"+semaphore.getQueueLength()+"个线程等待连接");
            System.out.println("当前可用连接数为："+semaphore.availablePermits());
            pool.add(connection);
            semaphore.release();
        }
    }




}
